package com.web.cloud.base.dao.provider;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.scripting.xmltags.*;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;

/**
 * 通用的批量逻辑删除
 * Created by liuhaiming on 2015/12/28
 */
public class BatchLogicDeleteMapperProvider extends MapperTemplate {
    public BatchLogicDeleteMapperProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    public SqlNode batchDelete(MappedStatement ms) {
        Class entityClass = this.getEntityClass(ms);
        LinkedList sqlNodes = new LinkedList();
        sqlNodes.add(new StaticTextSqlNode("UPDATE " + this.tableName(entityClass)));
        Set columnList = EntityHelper.getColumns(entityClass);
        EntityColumn drCol = null;
        EntityColumn idCol = null;
        Iterator forEachSqlNode = columnList.iterator();

        while(forEachSqlNode.hasNext()) {
            EntityColumn entityColumn = (EntityColumn)forEachSqlNode.next();
            if("dr".equalsIgnoreCase(entityColumn.getColumn())) {
                drCol = entityColumn;
            }

            if(entityColumn.isId()) {
                idCol = entityColumn;
            }
        }

        if(idCol == null) {
            throw new NullPointerException("id column is null !");
        } else if(drCol == null) {
            throw new NullPointerException("dr column is null !");
        } else {
            sqlNodes.add(new SetSqlNode(ms.getConfiguration(), new StaticTextSqlNode(drCol.getColumn() + " = 1 ")));
            ForEachSqlNode forEachSqlNode1 = new ForEachSqlNode(ms.getConfiguration(), new StaticTextSqlNode("#{item." + idCol.getProperty() + "}"), "list", "index", "item", " id in (", ")", ",");
            sqlNodes.add(new WhereSqlNode(ms.getConfiguration(), forEachSqlNode1));
            return new MixedSqlNode(sqlNodes);
        }
    }
}
